/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.core.service.impl;

import hu.glassy.core.model.Movie;
import hu.glassy.core.model.MovieRole;
import hu.glassy.core.model.PosterImage;
import hu.glassy.core.repositories.MovieRepository;
import hu.glassy.core.repositories.MovieRoleRepository;
import hu.glassy.core.service.MovieService;
import hu.glassy.core.util.PageableHelper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * Implementation of {@link MovieService}
 *
 * @author Alexander Molnár <molnar.alexander@sonrisa.hu>
 */
@Service
@Transactional(readOnly = true)
public class MovieServiceIml implements MovieService
{

  @Autowired
  private MovieRepository movieRepository;

  @Autowired
  private MovieRoleRepository movieRoleRepository;

  @Transactional(readOnly = false)
  @Override
  public void saveOrUpdate(final Movie movie)
  {
    Assert.notNull(movie);

    movieRepository.save(movie);
  }

  @Override
  public Movie findById(Long id)
  {
    return movieRepository.findOne(id);
  }

  @Override
  public List<Movie> getMovies()
  {
    return movieRepository.findAll();
  }

  @Override
  public void changePosterImage(Movie movie, String imagePath)
  {
    if (movie.getPosterImage() == null)
    {
      movie.setPosterImage(new PosterImage());
    }

    movie.getPosterImage().setImagePath(imagePath);
    movieRepository.save(movie);
  }

  @Override
  public Long countStaff(Movie movie)
  {
    return movieRoleRepository.countByMovie(movie);
  }

  @Override
  public List<MovieRole> getStaff(Movie movie, long start, long count)
  {
    Pageable pageable = PageableHelper.generatePageRequest(start, count, true, "priority");
    return movieRoleRepository.findByMovie(movie, pageable);
  }

  @Override
  public void addStaff(MovieRole movieRole)
  {
    movieRoleRepository.save(movieRole);
  }

}
